//
//  XQPublicIdentityAccureController.swift
//  Spark Peso
//
//  Created by 小琦 on 2025/2/6.
//

import UIKit
import Photos

class XQPublicIdentityAccureController: XQBaseController,UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    var successHandle: ((XQOrderPublishIdentityInfoModel,String,Int64) -> Void)?
    
    private lazy var bgImageView : UIImageView = {
        let imageView = UIImageView()
        imageView.image = UIImage(named: "detail_publish_bg")
        imageView.isUserInteractionEnabled = true
        return imageView
    }()
    
    private lazy var contentView : UIView = {
        let view = UIView()
        view.frame = CGRect(x: 15, y:UIDevice.xq_statusHeight() + 73, width: UIDevice.xq_width() - 30, height: UIDevice.xq_height() - UIDevice.xq_statusHeight() - 73)
        view.setRoundCorners([.topLeft,.topRight], radius: 16)
        view.backgroundColor = .white
        return view
    }()
    
    private lazy var tableView : UITableView = {
        let tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.separatorStyle = .none
        tableView.isScrollEnabled = true
        tableView.register(XQIdentityAccureCell.self, forCellReuseIdentifier: "XQIdentityAccureCell")
        
        return tableView
    }()
    
    private lazy var netBtn : UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("Next", for: .normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 20, weight: .medium)
        btn.setTitleColor(.white, for: .normal)
        btn.backgroundColor = .mainTextColor
        btn.layer.cornerRadius = 30
        btn.addTarget(self, action: #selector(nextClick), for: .touchUpInside)
        return btn
    }()
    
    var disciplinary : [String]? {
        didSet {
            if let arr = disciplinary {
                if !arr.isEmpty && identityType.count == 0 {
                    identityType = arr.first!
                }
            }
        }
    }
    var thousands : [String]?
    
    var chooseSeletedArr : [Bool] = [true,false]
    
    var identityType = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        makeUI()
        makeConstraints()
        
        startTime = XQTimeTool.nowTime()
    }
    
    private func makeUI() {
        self.navTitleColor = .white
        self.view.insertSubview(self.bgImageView, belowSubview: self.navigationBar)
        self.bgImageView.addSubview(self.contentView)
        self.contentView.addSubview(self.netBtn)
        self.contentView.addSubview(self.tableView)
    }
    
    private func makeConstraints() {
        self.bgImageView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        self.contentView.snp.makeConstraints { make in
            make.top.equalTo(UIDevice.xq_statusHeight() + 73)
            make.left.equalTo(15)
            make.right.equalTo(-15)
            make.bottom.equalTo(0)
        }
        self.netBtn.snp.makeConstraints { make in
            make.left.equalTo(32)
            make.right.equalTo(-32)
            make.height.equalTo(54)
            make.bottom.equalTo(-UIDevice.xq_safeTop() - 24)
        }
        self.tableView.snp.makeConstraints { make in
            make.top.equalTo(0)
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.bottom.equalTo(self.netBtn.snp.top).offset(-12)
        }
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let chooseSelected = chooseSeletedArr[section]
        if (section == 0) {
            return chooseSelected == true ? disciplinary?.count ?? 0 : 0
        }else {
            return chooseSelected == true ? thousands?.count ?? 0 : 0
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "XQIdentityAccureCell", for: indexPath) as! XQIdentityAccureCell
        let arr : [String]? = indexPath.section == 0 ? disciplinary : thousands
        
        if let list = arr {
            if (indexPath.row < list.count) {
                let value = list[indexPath.row];
                cell.content = value
                cell.selectArrow = identityType == value
            }
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 68
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = XQIdentityHeaderView()
        headerView.title = section == 0 ? "Recommended ID Type" : "Other Options"
        headerView.isSelect = chooseSeletedArr[section]
        headerView.onTapHandle = {[weak self] in
            guard let srongify = self else {return}
            srongify.headerClick(section: section)
        }
        return headerView
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 50
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let arr : [String]? = indexPath.section == 0 ? disciplinary : thousands
        
        guard let list = arr else {return}
        
        if (indexPath.row < list.count) {
            self.identityType = list[indexPath.row]
            self.tableView.reloadData()
        }
    }
    
    @objc private func nextClick() {
        
        showPopView()
        
        notifyRisk()
        
        self.startTime = XQTimeTool.nowTime()
    }
    
    private func headerClick(section : Int) {
        let chooseSelected = chooseSeletedArr[section]
        chooseSeletedArr[section] = !chooseSelected
        self.tableView.reloadSections(IndexSet(integer: section), with: .automatic)
    }
    
    private func showPopView() {
        let contentView = XQPublicIdentityPopView()
        contentView.frame = CGRect(x: 0, y:( UIDevice.xq_height() - 561) / 2, width: UIDevice.xq_width(), height: 561)
        contentView.sureHandle = {[weak self] in
            guard let srongify = self else {return}
            srongify.showActionSheet()
            XQHud.hidePop()
        }
        contentView.cancelHandle = {
            XQHud.hidePop()
        }
        XQHud.showPop(contentView)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let image = info[.originalImage] as? UIImage {
            let isCamera = picker.sourceType == .camera
            
            // 关闭图片选择器
            picker.dismiss(animated: true) {
                // 上传图片
                self.uploadPhoto(image: image, isCamera: isCamera)
            }
        }
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        dismiss(animated: true)
    }
    
    private func showActionSheet() {
        XQActionSheet.actionSheet(titles: ["Select form the album","Take Photo","Cancel"],headView: nil).show {[weak self] (index, title) in
            guard let srongify = self else {return}
            switch index {
            case 0 :
                srongify.openLibraryAlbum()
                break
            case 1 :
                srongify.openCamera()
                break
            case 2 :
                break
            default:
                break
            }
        }
    }
    
    private func openLibraryAlbum() {
        // 请求相册权限
        PHPhotoLibrary.requestAuthorization { status in
            DispatchQueue.main.async {
                if status == .authorized {
                    // 用户授权了相册权限
                    let picker = UIImagePickerController()
                    picker.sourceType = .savedPhotosAlbum
                    picker.delegate = self
                    picker.allowsEditing = true
                    self.present(picker, animated: true, completion: nil)
                } else if status == .denied {
                    // 用户拒绝了相册权限
                    self.showAccessDeniedAlert(message: "Please enable access to PhotoLibrary in Settings.")
                }
            }
        }
    }
    
    private func openCamera() {
        let authStatus = AVCaptureDevice.authorizationStatus(for: .video)

        // 请求相机权限
        AVCaptureDevice.requestAccess(for: .video) { granted in
            DispatchQueue.main.async {
                if granted {
                    if UIImagePickerController.isSourceTypeAvailable(.camera) {
                        let picker = UIImagePickerController()
                        picker.delegate = self
                        picker.sourceType = .camera
                        picker.cameraDevice = .rear
                        self.present(picker, animated: true, completion: nil)
                    }
                } else {
                    if authStatus == .denied {
                        self.showAccessDeniedAlert(message: "Please enable access to Camera in Settings.")
                    }
                }
            }
        }
    }
    
    private func showAccessDeniedAlert(message : String) {
        DispatchQueue.main.async {
            XQAlertManager.showDeniedAccessPopAlert(on: self, message:message)
        }
    }
    
    private func uploadPhoto(image : UIImage, isCamera : Bool) {
        let tens = isCamera ? "1" : "2"
        let spectrophotometer = "11"
        let internalData = identityType
        guard let imageData : Data = image.toMaxData(maxSizeInKB: 512) else {return}
        
        var params : [String : Any] = [
            "tens" : tens,
            "spectrophotometer" : spectrophotometer,
            "privilegeFaces" : imageData
        ]
        
        if (!internalData.isEmpty) {
            params["internal"] = internalData
        }
        
        XQHud.showLoading(controller: self)
        XQNetworkManager.shared.uploadImage(url: "/figures/firing", parameters: params,imageData: imageData) {[weak self] response, error in
            guard let srongify = self else {return}
            XQHud.hideLoading(controller: srongify)
            if (response?.object == 0) {
                if let model = XQOrderPublishIdentityInfoModel.deserialize(from: response?.procedure) {
                    srongify.getSuccessUserInfo(model: model)
                }
            }else {
                XQHud.showToast(message: response?.patients ?? "Network Connection Error")
            }
        }
    }
    
    private func getSuccessUserInfo(model : XQOrderPublishIdentityInfoModel) {
        self.navigationController?.popViewController(animated: true)
        successHandle?(model,identityType,startTime)
    }
   

    private func notifyRisk() {
        endTime = XQTimeTool.nowTime()
        
        XQAnalysisManager.shared.notifyRisk(numberType: "2", longitude: self.longitude, latitude: self.latitude, startT: self.startTime, endT: self.endTime, orderId: "")
    }
}
